package com.wx.service.impl;

import java.util.List;
import java.util.Stack;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import com.wx.dao.WxShortUrlMapper;
import com.wx.entity.WxShortUrl;
import com.wx.entity.WxShortUrlExample;
import com.wx.service.ShortURLService;

@Service("shortURLService")
@Slf4j
public class ShortURLServiceImpl implements ShortURLService {
	@Resource
	private WxShortUrlMapper wxShortUrlMapper;

	public static void main(String[] args) {
		System.out.println(_10_to_62(123456L));
	}
	
	@Override
	public String getShortURL(String key){
		try {
			long id = _62_to_10(key);
			WxShortUrlExample example = new WxShortUrlExample();
			example.createCriteria().andIdEqualTo(id);
			List<WxShortUrl> list= wxShortUrlMapper.selectByExample(example);
			if(list!=null&&!list.isEmpty()){
				return list.get(0).getShort_url();
			}
			return null;
		} catch (Exception e) {
			log.error("解析短地址失败");
			return null;
		}
	}
	
	@Override
	public String addShortURL(String url){
		try {
			WxShortUrl record = new WxShortUrl();
			record.setShort_url(url);
			int i = wxShortUrlMapper.insertSelective(record);
			if(i!=1){
				throw new Exception();
			}
			return _10_to_62(record.getId());
		} catch (Exception e) {
			log.error("生成短地址失败");
			return null;
		}
	}
	
	private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
		'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
		'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
		'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
		'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
		'X', 'Y', 'Z' };

	private static String _10_to_62(long number) {
		Long rest = number;
		Stack<Character> stack = new Stack<Character>();
		StringBuffer result = new StringBuffer(0);
		while (rest != 0) {
			stack.add(DIGITS[new Long((rest - (rest / 62) * 62)).intValue()]);
			rest = rest / 62;
		}
		for (; !stack.isEmpty();) {
			result.append(stack.pop());
		}
		return result.toString();
	}

	private static long _62_to_10(String sixty_str) throws Exception {
		int multiple = 1;
		long result = 0;
		Character c;
		for (int i = 0; i < sixty_str.length(); i++) {
			c = sixty_str.charAt(sixty_str.length() - i - 1);
			result += _62_value(c) * multiple;
			multiple = multiple * 62;
		}
		return result;
	}

	private static int _62_value(Character c) throws Exception {
		for (int i = 0; i < DIGITS.length; i++) {
			if (c == DIGITS[i]) {
				return i;
			}
		}
		throw new Exception();
	}
}
